var editor_cancel;
function cancelupload() {
	editor_cancel = true;
}
$(function() {
	$.subscribe("click_upload_cancel",__cancel,false);
	function __cancel(t,e,action) {
		cancelupload();
		$.UI.hide("image");
		$.get($(t).attr("srv"),{},function() {},"json");
	}
});
$.fn.upload = function(opt) {
	var reg = /^.+?\.(?:bmp|jpg|jpeg|gif|png)$/i;
	function showError(type) {
		var msg = '<div class="uploadformat"><div class="formaterror"></div><div class="infotxt">#msg#</div></div>';
		if(type == 'format') {
			msg = msg.replace("#msg#" , "请上传jpg,jpeg,gif,bmp,png格式的图片。");
		} else if(type == 'timeout') {
			msg = msg.replace("#msg#" , "与服务器的连接超时,请重试。")
		} else if(type == 'size') {
			msg = msg.replace("#msg#" , "目前只支持小于2M的图片上传,请选择其他图片。")
		}
		$.alert(msg,{liveTime:0,type:"image"});
	}
	return this.each(function() {
		var $this = $(this);
		var $form = $("<form></form>");
		$form.addClass("uploadform");
		var $input = $("<input type='file' hideFocus=true name='" + opt.name + "'/>");
		$input.change(function() {
			var val = $(this).val();
			if(val) {
				if(reg.test(val)) {
					$form.submit();
				} else {
					showError('format');
				}
			}
		});
		$form.append($input);
		$form.append("<input type='hidden' name='millis'/>");
		$input.css({
			width:$this.outerWidth(),
			height:$this.outerHeight()
		});
		var position = $this.css('position');
		if(position != 'absolute' && position != 'relative') {
			$this.css('position' , 'relative');
		}
		$this.append($form);
		var justUpload;
		$form.show().attr({
			action : opt.action,
			enctype : "multipart/form-data",
			method : "POST"
		}).ajaxForm({
			dataType : "json",
			timeout:150000,
			beforeSubmit : function() {
				editor_cancel = false;
				$form.hide();
				justUpload = new Date().getTime();
				$form.find('input[name="millis"]').val(justUpload);
				$this.notice("<div class='uploadwait'><span class='loadimg'>请等待图片上传...</span><span class='cancelupload'><a href='javascript:;' srv='../CancelUpload?millis=" + justUpload + "' class='ac_upload_cancel'>取消上传</a></span></div>" , {liveTime:0,direction:"down",align:"center",type:"image"});
			},
			success : function(d) {
				$.UI.hide("image");
				if(!editor_cancel) {
					var code = d.code;
					if(!code) {
						$this.notice("<div class='showimg'><div class='alignleft'><span>" + d.filename + "</span><a href='javascript:;' srv='../CancelUpload?millis=" + justUpload + "' class='ac_delete_image'>删除</a></div><img src='" + d.url + "' /></div>" , {liveTime:0,direction:"down",align:"center",type:"image"});					
						if(opt.successFun) {
							opt.successFun(d);	
						}	
					} else {
						showError("size");
						if(opt.errorFun) {
							opt.errorFun(d);	
						}
					}			
				}
				$form.show().get(0).reset();
			},
			error : function() {
				$.UI.hide("image");
				showError('timeout');
				$form.show().get(0).reset();
			}
		});
	});
};